<template>
  <div class="draft-notice-container">
    <!-- 查询表单 -->
    <div class="search-form">
      <el-form :model="formData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="职位名称">
              <el-input v-model="formData.positionName" placeholder="请输入职位名称" clearable @keyup.enter="onQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="18" style="text-align: right">
            <el-button type="primary" @click="onQuery">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="success" @click="showAddForm = true; loadDeptList()">新增</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 主内容区 - 左右布局 -->
    <div class="main-content">
      <!-- 左侧职位表格 -->
      <div class="left-content">
        <div class="table-header">
          <h3>职位表</h3>
        </div>
        <el-table :data="nodeList" border style="width: 100%" v-loading="loading" :row-style="{ height: '45px' }"
          highlight-current-row @current-change="handlePositionSelect">
          <el-table-column prop="id" label="职位编号" align="center" />
          <el-table-column prop="name" label="职位名称" min-width="200" align="center" />
          <el-table-column fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button link size="small" type="primary" @click="editNode(scope.row)">修改</el-button>
              <el-button link size="small" type="danger" @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination">
          <el-pagination v-model:current-page="page.currentPage" v-model:page-size="page.pageSize" :total="page.total"
            layout="total, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handlerCurrentPage" />
        </div>
      </div>

      <!-- 右侧员工表格 -->
      <div class="right-content">
        <div class="table-header">
          <h3>{{ Data.positionName || '职位' }}员工表</h3>
        </div>
        <el-table :data="employees" border style="width: 100%" v-loading="loading" :empty-text="emptyText">
          <el-table-column prop="empId" label="员工ID" align="center" />
          <el-table-column prop="name" label="姓名" align="center" />
          <el-table-column prop="deptName" label="部门" align="center" />
          <el-table-column prop="positionName" label="职位" width="150" align="center" />
          <el-table-column prop="age" label="年龄" align="center" />
          <el-table-column label="上下级关系" width="120" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isLeader === 1 ? 'success' : ''">
                {{ scope.row.isLeader === 1 ? '领导' : '员工' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加职位对话框 -->
    <el-dialog v-model="showAddForm" title="添加职位" width="30%" :close-on-click-modal="false" align-center @close="resetForm">
      <el-form :model="form" label-width="100px">
        <el-form-item label="所属部门">
          <el-select v-model="newDeptName" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位名称">
          <el-input v-model="newPositionName" placeholder="请输入职位名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑职位对话框 -->
    <el-dialog v-model="showEditForm" title="修改职位" width="30%" :close-on-click-modal="false" align-center>
      <el-form :model="Data" label-width="100px">
        <el-form-item label="职位编号">
          <el-input v-model="Data.positionId" disabled />
        </el-form-item>
        <el-form-item label="原职位名称">
          <el-input v-model="Data.positionName" disabled />
        </el-form-item>
        <el-form-item label="新职位名称">
          <el-input v-model="Data.editPositionName" placeholder="请输入职位名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditForm = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog v-model="showConfirmDeleteDialog" title="确认删除" width="25%" align-center>
      <p style="text-align: center">是否真的删除 <strong>{{ deleteData.deletePositionName }}</strong> 职位？</p>
      <template #footer>
        <el-button @click="showConfirmDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="submitDeleteForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import {
  pagePosition,
  addPosition,
  editPosition,
  deletePosition,
  getEmpsByPositionId,
} from "../../api/position.js";
import { getAllDepts } from "../../api/dept.js";

export default {
  data() {
    return {
      formData: {
        positionName: "",
        pageNum: "",
        pageSize: "",
      },
      name: "", //职位名称
      newPositionName: "", //新添加的职位名称
      Data: {
        positionId: "", //职位ID
        positionName: "", //职位名称
        editPositionName: "", //新编辑的职位名称
      },
      deleteData: {
        deletePositionId: "", //要删除的职位ID
        deletePositionName: "", //要删除的职位名称
      },
      nodeList: [], //职位列表
      employees: [], // 员工信息
      deptList: [], // 部门列表
      newDeptName: "", //新添加的部门名称
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      showAddForm: false, // 添加职位表单显示与隐藏
      showEditForm: false, // 编辑职位表单显示与隐藏
      showConfirmDeleteDialog: false, // 删除确认对话框显示与隐藏
    };
  },
  computed: {
    emptyText() {
      if (this.Data.positionName) {
        return "NO DATA";
      }
      return "请先选择左侧职位";
    },
  },
  methods: {
    onQuery() {
      console.log("查询");
      this.page.currentPage = 1; // 查询时重置到第一页
      this.formData.pageNum = this.page.currentPage; // 设置查询的页码
      this.getList();
    },

    onReset() {
      console.log("重置");
      this.formData.positionName = "";
    },

    onAdd() {
      console.log("新增");
      this.showAddForm = true;
    },

    //当页码发生改变时执行函数
    handlerCurrentPage(number) {
      console.log("分页");
      this.formData.pageNum = number;
      this.page.currentPage = number;
      this.getList();
    },

    search(row) {
      console.log("查看");
      this.$nextTick(() => {
        this.Data = {
          positionId: row.id,
          positionName: row.name,
        };
      });

      // 获取该职位的员工信息
      let params = {
        positionId: row.id,
      };

      this.getEmployeesByPositionId(params); // 调用获取员工信息的函数
    },

    resetForm() {
      this.showAddForm = false; // 关闭添加职位表单
      this.newPositionName = '';
      this.newDeptName = '';
      this.showAddForm = false;
    },

    //api-获取所有部门
    loadDeptList() {
      getAllDepts()
        .then((res) => {
          if (res.flag) {
            this.deptList = res.result; // 将部门列表存储到 deptList 中
          } else {
            this.$message.error(res.reason || "获取部门列表失败");
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("请求失败，请稍后重试");
        });
    },

    //api-获取员工信息
    getEmployeesByPositionId(positionId) {
      getEmpsByPositionId(positionId)
        .then((response) => {
          console.log(response);
          if (response.flag) {
            console.log(response.reason); // 打印后端返回的成功信息
            this.employees = response.result; // 将后端返回的员工信息赋值给 employees
          } else {
            console.error(response.reason); // 打印后端返回的失败信息
            this.$message.error(response.reason); // 弹出失败提示
            this.employees = []; // 清空员工信息
          }
        })
        .catch((error) => {
          console.error("获取员工信息失败", error); // 打印网络请求错误信息
          this.$message.error("获取员工信息失败，请稍后再试"); // 弹出失败提示
          this.employees = []; // 清空员工信息
        });
    },

    editNode(row) {
      console.log("修改");
      this.$nextTick(() => {
        this.Data = {
          positionId: row.id,
          positionName: row.name,
        };
      });
      this.showEditForm = true; // 显示编辑职位表单
    },

    submitEditForm() {
      console.log("提交修改");
      let params = {
        positionId: this.Data.positionId,
        positionName: this.Data.editPositionName,
      };
      editPosition(params)
        .then((response) => {
          if (response.flag) {
            console.log(response.reason); // 打印后端返回的成功信息
            this.$message.success(response.reason); // 弹出成功提示
            this.Data.positionName = response.result.name; // 更新职位名称
            this.Data.positionId = response.result.id;
            this.getList(); // 刷新表格数据
            this.getEmployeesByPositionId({ positionId: this.Data.positionId }); // 刷新员工表
          } else {
            console.error(response.reason); // 打印后端返回的失败信息
            this.$message.error(response.reason); // 弹出失败提示
          }
        })
        .catch((error) => {
          console.error("修改职位失败", error); // 打印网络请求错误信息
          this.$message.error("修改职位失败，请稍后再试"); // 弹出失败提示
        });

      this.showEditForm = false; // 提交后关闭表单
      this.Data.editPositionName = ""; // 清空编辑数据
      this.newPositionName = ""; // 清空新职位名称
    },

    del(row) {
      console.log("删除");
      this.deleteData.deletePositionId = row.id; // 设置要删除的职位编号
      this.deleteData.deletePositionName = row.name; // 设置要删除的职位名称
      this.showConfirmDeleteDialog = true; // 打开确认删除对话框
    },

    submitDeleteForm() {
      console.log("提交删除");
      let params = {
        positionId: this.deleteData.deletePositionId,
      };
      const deletePositionName = this.deleteData.deletePositionName; // 存储要删除的职位名称
      deletePosition(params)
        .then((response) => {
          if (response.flag) {
            console.log(response.reason); // 打印后端返回的成功信息
            this.$message.success(response.reason); // 弹出成功提示

            // 检查当前查看的职位是否与要删除的职位相同
            console.log(this.Data.positionName);
            console.log(deletePositionName);
            if (this.Data.positionName === deletePositionName) {
              // 清空员工表内容
              this.employees = [];
              // 更新员工表的标题为默认值或空值
              this.Data.positionName = "";
            }
            this.getList(); // 刷新表格数据
          } else {
            console.error(response.reason); // 打印后端返回的失败信息
            this.$message.error(response.reason); // 弹出失败提示
          }
        })
        .catch((error) => {
          console.error("删除职位失败", error); // 打印网络请求错误信息
          this.$message.error("删除职位失败，请稍后再试"); // 弹出失败提示
        });

      this.showConfirmDeleteDialog = false; // 提交后关闭对话框
      this.deleteData.deletePositionId = ""; // 清空删除数据
      this.deleteData.deletePositionName = ""; // 清空删除数据
    },

    submitAddForm() {
      console.log("提交新增");
      let params = {
        positionName: this.newPositionName,
        deptName: this.newDeptName,
      };
      addPosition(params)
        .then((response) => {
          if (response.flag) {
            console.log(response.reason); // 打印后端返回的成功信息
            this.$message.success(response.reason); // 弹出成功提示
            this.getList();
          } else {
            console.error(response.reason); // 打印后端返回的失败信息
            this.$message.error(response.reason); // 弹出失败提示
          }
        })
        .catch((error) => {
          console.error("添加职位失败", error); // 打印网络请求错误信息
          this.$message.error("添加职位失败，请稍后再试"); // 弹出失败提示
        });

      this.showAddForm = false; // 提交后关闭表单
      this.newPositionName = ""; // 清空表单数据
      this.newDeptName = ""; // 清空表单数据
    },

    //API-获取分页数据
    getList() {
      this.formData.pageSize = this.page.pageSize;
      pagePosition(this.formData).then((res) => {
        console.log(res);
        this.nodeList = res.result.records;
        this.page.total = res.result.total;
        this.page.currentPage = res.result.current;
      });
    },
    handlePositionSelect(position) {
      if (position) {
        this.Data = {
          positionId: position.id,
          positionName: position.name,
        };
        this.getEmployeesByPositionId({ positionId: position.id });
      }
    },
  },
  mounted() {
    this.getList();
    this.loadDeptList(); // 加载部门列表
  },
};
</script>

<style scoped>
.draft-notice-container {
  padding: 20px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.search-form {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.main-content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  gap: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-sizing: border-box;
}

.left-content,
.right-content {
  flex: 1;
  min-width: 600px;
  overflow-x: auto;
}

@media (max-width: 1400px) {

  .left-content,
  .right-content {
    min-width: 100%;
  }
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.table-header {
  margin-bottom: 15px;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.el-table {
  width: 100%;
  table-layout: fixed;
}
</style>